<!--
 * @author  dumeng
 展示管理
-->
<template>
  <section class="reveal-manage">
    <section class="reveal-manage-title">新建/编辑</section>
    <section v-loading="loading" class="reveal-manage-main">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" class="form">
        <el-form-item label="位置" prop="location">
          <el-select v-model="form.location" placeholder="请选择分类" clearable :style="{width:'100%'}">
            <el-option v-for="(item, index) in classifys" :key="index" :label="item.dictName" :value="item.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" maxlength="20" show-word-limit/>
        </el-form-item>
        <el-form-item label="图片" prop="carouselImg" required>
          <image-upload
              v-show="form.location == 'ZSGL_YFL' "
              :key="uploadFile.imagecropperKey"
              v-model="form.carouselImg"
              :preview-id="uploadFile.viewId"
              :forever="true"
              :width="654"
              :view="uploadFile.view"
              :height="120"
              :no-circle="true"
              :no-rotate="false"
              lang-type="zh"
              :is-oss="uploadFile.isOss"
              @changeOssPath="(path) =>{uploadFile.viewId = path}"
          />
          <image-upload
              v-show="form.location == 'ZSGL_LB'"
              :key="uploadFile.imagecropperKey + 1"
              v-model="form.carouselImg"
              :preview-id="uploadFile.viewId"
              :forever="true"
              :width="702"
              :view="uploadFile.view"
              :height="310"
              :no-circle="true"
              :no-rotate="false"
              lang-type="zh"
              :is-oss="uploadFile.isOss"
              @changeOssPath="(path) =>{uploadFile.viewId = path}"
          />
          <image-upload
              v-show="form.location == 'ZSGL_JNZQZS'"
              :key="uploadFile.imagecropperKey + 2"
              v-model="form.carouselImg"
              :preview-id="uploadFile.viewId"
              :forever="true"
              :width="120"
              :view="uploadFile.view"
              :height="120"
              :no-circle="true"
              :no-rotate="false"
              lang-type="zh"
              :is-oss="uploadFile.isOss"
              @changeOssPath="(path) =>{uploadFile.viewId = path}"
          />
          <image-upload
              v-show="form.location == 'ZSGL_PCLB'"
              :key="uploadFile.imagecropperKey + 3"
              v-model="form.carouselImg"
              :preview-id="uploadFile.viewId"
              :forever="true"
              :width="1200"
              :view="uploadFile.view"
              :height="360"
              :no-circle="true"
              :no-rotate="false"
              lang-type="zh"
              :is-oss="uploadFile.isOss"
              @changeOssPath="(path) =>{uploadFile.viewId = path}"
          />
        </el-form-item>
        <el-form-item label="链接类型" prop="linkType">
          <el-radio-group v-model="form.linkType">
            <el-radio label="1">内部链接</el-radio>
            <el-radio label="2">外部链接</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="链接地址" prop="linkAddress">
          <el-input v-model="form.linkAddress" placeholder="请输入链接地址" maxlength="20" show-word-limit/>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <!-- <el-input v-model.number="form.sort" placeholder="请输入排序号（值越小，越靠前）" /> -->
          <el-input v-model.number="form.sort" placeholder="请输入排序号（值越大，越靠前）" maxlength="20" show-word-limit />
        </el-form-item>
      </el-form>
    </section>
    <section class="reveal-manage-footer">
      <el-button style="padding: 10px 30px;" @click="handleCancel()">取 消</el-button>
      <el-button type="primary" @click="onSubmint('form')">确 定</el-button>
    </section>
  </section>
</template>

<script>
import ImageUpload from '@/components/ImageUpload'
import { getDictByCode, insert, update, get } from '../api'

export default {
  name: 'RevealManage',
  components: { ImageUpload },
  data() {
    return {
      loading: false,
      form: {
        id: '',
        name: '',
        carouselImg: '',
        linkType: '1',
        sort: '',
        linkAddress: '',
        status: '0',
        location: '' // 默认首页
      },
      rules: {
        location: [{ required: true, message: '请选择位置', trigger: 'change' }],
        linkType: [{ required: true, message: '请选择链接类型', trigger: 'change' }],
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur' }
        ],
        linkAddress: [{ required: true, message: '请输入链接地址', trigger: 'blur' }],
        carouselImg: [{ required: true, message: '请上传引导图', trigger: 'change' }]
      },
      classifys: [],
      state: 'create',
      uploadFile: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0,
        showUpload: false,
        accept: '',
        fileType: '',
        fileIndex: 0,
        isOss: sessionStorage.getItem('FILE_SAVE_THIRD_CONFIG') || false
      }
    }
  },

  created() {
    this.state = this.$route.query.type === 'u' ? 'update' : 'create'
    this.t = this.$route.query.t || ''
    this.getClassify()
    if (this.$route.query.type === 'u') {
      if (!this.$route.query.i) {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.$router.back()
          }
        })
      } else {
        this.getData(this.$route.query.i)
      }
    }
  },
  methods: {

    getClassify() {
      return new Promise((resolve, reject) => {
        getDictByCode('ZSGL').then(res => {
          this.classifys = (res.data.data && res.data.data.length > 0) ? res.data.data[0].list : []
          if (this.state === 'create') {
            this.form.location = this.classifys[0].dictValue
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    handleCancel() {
      this.$router.push({ path: this.$filterPath('index'), query: { t: this.t } })
    },

    onSubmint() {
      if (this.state === 'create') {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const params = Object.assign({}, this.form)
            return new Promise((resolve, reject) => {
              insert(params).then(() => {
                this.dialogVisible = false
                loading.close()
                this.$message({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 2000
                })
                this.handleCancel()
              }).catch(error => {
                reject(error)
                loading.close()
              })
            })
          } else {
            return false
          }
        })
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })

            const params = Object.assign({}, this.form)
            return new Promise((resolve, reject) => {
              update(params).then(() => {
                this.dialogVisible = false
                loading.close()
                this.$message({
                  title: '成功',
                  message: '修改成功',
                  type: 'success',
                  duration: 2000
                })
                this.handleCancel()
              }).catch(error => {
                reject(error)
                loading.close()
              })
            })
          } else {
            return false
          }
        })
      }
    },

    /**
     * 根编辑回显
     */
    getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({ id: id }).then(res => {
          loading.close()
          const data = res.data.data
          for (const key in this.form) {
            this.form[key] = data[key]
          }
          this.uploadFile.viewId = data.carouselImgUrl
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">

.reveal-manage {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;

  .reveal-manage-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;

    &:before {
      content: '';
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .reveal-manage-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: hidden;

    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }

    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }

    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }

    &:hover {
      overflow: auto;
    }

    .form {
      width: 1000px !important;
      margin: 0 auto;

      .el-select {
        width: 100%;
      }

      .line {
        text-align: center;
      }
    }
  }

  .reveal-manage-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }

  .image-upload-dialog {
    .icon-wrap {
      width: 300px;
      height: 160px;
      margin: 0 auto;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(247, 247, 248, 1);
      border: 1px solid rgba(226, 227, 232, 1);
      border-radius: 4px;

      .avatar-uploader-icon {
        font-size: 48px;
        color: #dadada;
        width: 300px;
        text-align: center;
      }
    }

    .upload-img {
      display: block;
      width: 300px;
      height: 160px;
      border-radius: 4px;
    }
  }
}
</style>
